//
//  SettingsViewController.m
//  TuiTe
//
//  Created by 张 霄鹤 on 10-3-12.
//  Copyright 2010 xhzhang. All rights reserved.
//

#import "SettingsViewController.h"

#import "Account.h"
#import "DataManager.h"
#import "TwitterClient.h"
#import "ViewControllerChooser.h"
#import "AddAccountViewController.h"


@implementation SettingsViewController

/*
- (id)initWithStyle:(UITableViewStyle)style {
    // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
    if (self = [super initWithStyle:style]) {
    }
    return self;
}
*/


- (void)viewDidLoad {
    [super viewDidLoad];
	
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
	
	NSUserDefaults *usrDefaults = [NSUserDefaults standardUserDefaults];
	currentUserIndex = [usrDefaults integerForKey:@"cu"];
	
	currentSUIndex = [[DataManager sharedManager] getShortenURLSettingIndex];
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
	self.tabBarController.navigationItem.title = @"Settings";
	[self.tableView reloadData];
}

/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
	[super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
	[super viewDidDisappear:animated];
}
*/

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	NSInteger ret = 0;
	DataManager *dm;
	NSArray *dt;
	switch (section) {
		case 0:
			{
				DataManager *dm = [DataManager sharedManager];
				ret = [dm numberOfAccounts] + 1;
			}
			break;
		case 1:
			ret = 1;
			break;

		case 2:
		{
			// TODO 目前包含 shortenurl setting
			dm = [DataManager sharedManager];
			dt = [dm getShortenURLServices];
			if(dt){
				ret = [dt count];
			}
			
		}
			break;

		default:
			break;
	}
    return ret;
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    
    // Set up the cell...
	NSInteger section = indexPath.section;
	NSInteger row = indexPath.row;
	
	NSString *ct = @"";
	DataManager *dm = [DataManager sharedManager];
	if(section == 0){
		// TODO Account Settings
		
		NSInteger aclen = [dm numberOfAccounts];
		if(row < aclen){
			Account *acc = [dm getAccount:row];
			ct = acc.name;
			if(row == currentUserIndex){
				cell.accessoryType = UITableViewCellAccessoryCheckmark;
			}
		}else{
			// TODO Add Account Cell
			ct = @"Add Account";
			cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
		}
		
		//cell.selectionStyle = UITableViewCellSelectionStyleNone;
	} else if (section == 1) {
		// TODO Confirm
		
	} else if(section == 2){
		// TODO ShortenURL Setting
		NSArray *arr = [dm getShortenURLServices];
		if(arr){
			id obj = [arr objectAtIndex:row];
			NSDictionary *dt = (NSDictionary *)obj;
			ct = [dt objectForKey:@"txt"];
		}
		if(row == currentSUIndex){
			cell.accessoryType = UITableViewCellAccessoryCheckmark;
		}else{
			cell.accessoryType = UITableViewCellAccessoryNone;
		}
	}
	
	cell.textLabel.text = ct;
	
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
	// AnotherViewController *anotherViewController = [[AnotherViewController alloc] initWithNibName:@"AnotherView" bundle:nil];
	// [self.navigationController pushViewController:anotherViewController];
	// [anotherViewController release];
	NSInteger section = indexPath.section;
	NSInteger row = indexPath.row;
	if(section == 0){
		UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
		[cell setSelected:NO];
		// TODO 账号设置
		DataManager *dm = [DataManager sharedManager];
		NSInteger aclen = [dm numberOfAccounts];
		if(row < aclen){
			// TODO 编辑相应账号
			if(currentUserIndex != row){
				NSIndexPath *nin = [NSIndexPath indexPathForRow:currentUserIndex inSection:section];
#ifdef DEBUG
				NSLog(@"%d %d",nin.section,nin.row);
#endif
				UITableViewCell *tc = [tableView cellForRowAtIndexPath:nin];
				if(tc){
					tc.accessoryType = UITableViewCellAccessoryNone;
				}
				NSUserDefaults *usrDefaults = [NSUserDefaults standardUserDefaults];
				[usrDefaults setInteger:row forKey:@"cu"];
				currentUserIndex = row;
				cell.accessoryType = UITableViewCellAccessoryCheckmark;
				Account *acc = [dm getAccount:row];
				if(acc){
					TwitterClient *client = [TwitterClient getInstance];
					[client changeAccount:acc.name withPass:acc.pass];
				}
			}
		}else{
			// TODO 增加账号
			AddAccountViewController *add = (AddAccountViewController *)[[ViewControllerChooser sharedChooser] choose:VC_ADD_ACCOUNT];
			[self.navigationController pushViewController:add animated:YES];
		}		
	}else if(section == 2){
		UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
		[cell setSelected:NO];
		// TODO 账号设置
		if(row != currentSUIndex){
			DataManager *dm = [DataManager sharedManager];
			[dm setShortenURLSettingIndex:row];
			NSIndexPath *nin = [NSIndexPath indexPathForRow:currentSUIndex inSection:section];
			UITableViewCell *tc = [tableView cellForRowAtIndexPath:nin];
			if(tc){
				tc.accessoryType = UITableViewCellAccessoryNone;
			}
			currentSUIndex = row;
			cell.accessoryType = UITableViewCellAccessoryCheckmark;
		}
	}
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
	NSString *ret = @"";
	switch (section) {
		case 0:
			ret = NSLocalizedString(@"ADD_ACNT_HEADER",@"");
			break;
		case 1:
			ret = NSLocalizedString(@"CONFIRM",@"");
			break;
		case 2:
			ret = NSLocalizedString(@"SHORTENSERVICE",@"");
			break;

		default:
			break;
	}
	return ret;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


- (void)dealloc {
    [super dealloc];
}


@end

